package com.medical.sys.web.controller;

import com.medical.common.DTJsonResult;
import com.medical.common.JsonResult;
import com.medical.common.TreeNode;
import com.medical.sys.model.Organization;
import com.medical.sys.model.User;
import com.medical.sys.service.OrganizationService;
import com.medical.sys.service.UserService;
import com.medical.track.service.DoctorService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
//用户管理
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private OrganizationService organizationService;


    //测试类
    @ApiOperation(value="", notes="")
    @RequestMapping(value ="/test",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult test(@RequestParam("id")String id,
                            @RequestParam("roleids")List<String>roleids){
        User user=userService.selectByPrimaryKey(id);
        user.setRoleIds(roleids);
        userService.updateUser(user);
        return new JsonResult("测试用","",user);
    }


    //返回user表的总数据的条数
    @ApiOperation(value="返回user表的总数据的条数", notes="返回user表的总数据的条数")
    @RequestMapping(value = "/getsize",method = RequestMethod.GET)
    @ResponseBody
    public String getSize(){
        return String.valueOf(userService.getUsers().size());
    }

    //返回门店集合
    @ApiOperation(value="返回门店集合", notes="返回门店集合")
    @RequestMapping(value = "/getorg", method = RequestMethod.GET)
    @ResponseBody
    //把查询到的oraganization表中总数据的id，name，peopleId加到TreeNode中，返回TreeNode集合
    public JsonResult getOrgList() {
        try {
            List<TreeNode> list=organizationService.getList();
            return new JsonResult("200","",list);
        } catch (Exception e) {
            return new JsonResult("500",e.getMessage());
        }
    }


    /**
     *
     * @param query
     * @param page
     * @param pageSize
     * @param sortColumn
     * @param sortDir
     * @return
     */
    //模糊查询
    @ApiOperation(value="模糊查询", notes="模糊查询")
    @RequestMapping(value="/",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getUser(@RequestParam("query")String query,
                            @RequestParam("page")Integer page,
                            @RequestParam("pageSize")Integer pageSize,
                            @RequestParam("sortColumn")String sortColumn,
                            @RequestParam("sortDir")String sortDir){


        return new JsonResult(userService.searchUsers(query, page, pageSize, sortColumn, sortDir));
    }

    //根据id返回user对象
    @ApiOperation(value="根据id返回user对象", notes="根据id返回user对象")
    @RequestMapping(value="/getone/{id}",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult getOne(@PathVariable String id){
        try {
            User user = userService.selectByPrimaryKey(id);
            return new JsonResult("200", "", user);
        }catch (Exception e){
            return new JsonResult("500",e.getMessage());
        }
    }

    //根据orgId返回user数组
    @ApiOperation(value="根据orgId返回user数组", notes="根据orgId返回user数组")
    @RequestMapping(value="/getuser/{orgid}",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult searchByOrgAjax(@RequestParam("orgid")String orgId,
                                      @RequestParam("page")Integer page,
                                      @RequestParam("pageSize")Integer pageSize,
                                      @RequestParam("sortColumn")String sortColumn,
                                      @RequestParam("sortDir")String sortDir) {
        try {
            return new JsonResult(userService.findUsersByOrgId(orgId, page, pageSize, sortColumn, sortDir));
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }


    //新增
    @ApiOperation(value="新增", notes="新增")
    @RequestMapping(value="/post",method=RequestMethod.POST)
    @ResponseBody
    public JsonResult add(@RequestParam("username" )String username, @RequestParam("password" )String password ,
                          @RequestParam("fullname" )String fullname, @RequestParam("email" )String email,
                          @RequestParam("phone" )String phone, @RequestParam("organizationId" )String organizationId,
                          @RequestParam("roleIds")List<String>roleIds, @RequestParam("organizationIds" )List<String>organizationIds) {
        try {
            User user=new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setFullname(fullname);
            user.setEmail(password);
            user.setPhone(phone);
            user.setOrganizationId(organizationId);
            user.setRoleIds(roleIds);
            user.setOrganizationIds(organizationIds);
            user.setDeleted(false);
            userService.saveUser(user);
            return new JsonResult("200","",user);
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }
    //根据id编辑
    @ApiOperation(value="根据id编辑", notes="根据id编辑")
    @RequestMapping(value="/patch/{id}",method=RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(@PathVariable String id,@RequestParam("username" )String username, @RequestParam("password" )String password ,
                           @RequestParam("fullname" )String fullname, @RequestParam("email" )String email,
                           @RequestParam("phone" )String phone, @RequestParam("organizationId" )String organizationId,
                           @RequestParam("roleIds")List<String>roleIds, @RequestParam("organizationIds" )List<String>organizationIds){
        try {
            User user=userService.selectByPrimaryKey(id);
            user.setUsername(username);
            user.setPassword(password);
            user.setFullname(fullname);
            user.setEmail(password);
            user.setPhone(phone);
            user.setOrganizationId(organizationId);
            user.setRoleIds(roleIds);
            user.setOrganizationIds(organizationIds);
            userService.updateUser(user);
            return new JsonResult("200","",user);
        }catch (Exception e){
            return new JsonResult("500",e.getMessage());
        }
    }
    //根据id删除
    @ApiOperation(value="根据id删除", notes="根据id删除")
    @RequestMapping(value="delete/{id}",method=RequestMethod.POST)
    public JsonResult delete(@PathVariable String id) {

        try {
            doctorService.deleteDoctor(id);
            userService.deleteUser(id);
            return new JsonResult("200", "操作成功");
        } catch (Exception e) {
            return new JsonResult("500", e.getMessage());
        }
    }


    //未用到此类
    @RequestMapping(value="/treeforrole")
    @ResponseBody
    public List<TreeNode> treeForRole(HttpServletRequest req){
        List<TreeNode> tree = new ArrayList<TreeNode>();
        String roleId = req.getParameter("roleId");
        List<User> roleUsers = userService.getUsersByRoleId(roleId);//返回该角色的所有用户
        List<User> users = userService.getUsers();//返回所有用户m
        List<Organization> organizations = organizationService.getOrganizations();//返回全部门店
        TreeNode notn = new TreeNode();
        notn.setId("-1");
        notn.setName("未分配");
        notn.setParentId("0");
        tree.add(notn);
        for(Organization o : organizations){//遍历全部门店存到otn对象中
            TreeNode otn = new TreeNode();
            otn.setId(String.valueOf(o.getId()));
            otn.setName(o.getName());
            otn.setParentId("0");
            tree.add(otn);
            int uCount = users.size();
            for(int i=0;i<uCount;i++){
                User user = users.get(i);
                //user有门店id的话
                if(String.valueOf(o.getId()).equals(user.getOrganizationId())){
                    //
                    tree.add(userToTree(user, String.valueOf(o.getId()), roleUsers));
                    users.remove(i);
                    break;
                }
            }
        }
        for(User user : users){
            tree.add(userToTree(user, "-1", roleUsers));
        }
        return tree;
    }

    private TreeNode userToTree(User user, String parentId, List<User> checkUsers){
        TreeNode tn = new TreeNode();
        tn.setId(user.getId());
        tn.setName(user.getUsername() + "-" + user.getFullname());
        tn.setParentId(parentId);
        int ruCount = checkUsers.size();
        for(int j=0;j<ruCount;j++){
            User rUser = checkUsers.get(j);
            if(rUser.getId().equals(user.getId())){
                tn.setChecked(true);
                checkUsers.remove(j);
                break;
            }
        }
        return tn;
    }

}
